package com.site.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by shengquan.wu on 2018/6/5.
 */
@Aspect
@Component
public class HttpAspect {

    /**
     * 使用日志
     */
    private final static Logger log = LoggerFactory.getLogger(HttpAspect.class);


    /**
     * ============================================
     * 1.0 直接在注解里面写切入点
     */

    /**
     * @Before 注解会在方法执行前执行
     */
//    @Before("execution(public * com.site.controller.UserController.*(..))")
//    public void logBefore(){
//        System.out.println("log in @before");
//    }
//
//    @After("execution(public * com.site.controller.UserController.*(..))")
//    public void logAfter(){
//        System.out.println("log in @after");
//    }


    /**
     * ============================================
     * 2.0 单独定义切入点， 在注解里面引用
     */
    @Pointcut("execution(public * com.site.controller.UserController.*(..))")
    public void logHttp(){
    }

    @Before("logHttp()")
    public void logBefore(JoinPoint joinPoint){
        log.info("using slf4j in before");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //url
//        log.info("url={}", request.getRequestURL());

        //method
//        log.info("method={}", request.getMethod());

        //ip
//        log.info("ip={}", request.getRemoteAddr());

        //类方法
//        log.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //参数
//        log.info("args={}", joinPoint.getArgs());



    }

    @After("logHttp()")
    public void logAfter(){
        log.info("using slf4j in after");
    }

    @AfterReturning(returning = "object", pointcut = "logHttp()")
    public void doAfterReturning(Object object){
        log.info("response={}", object.toString());
    }



}
